Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Single Number II

Problem Statement

Given an array of integers nums where each element appears three times, and one element appears exactly once, return the single element.

Note: You must solve the problem with linear runtime complexity and use only constant extra space.

Examples

  • Example 1:
    • Input: nums = [4, 3, 3, 3]
    • Expected Output: 4
    • Justification: 4 is the only number that appears once, while 3 appears three times.
  • Example 2:
    • Input: nums = [99, 1, 99, 99, 2, 2, 2]
    • Expected Output: 1
    • Justification: 1 appears exactly once whereas 99 and 2 each appear three times.
  • Example 3:
    • Input: nums = [0, 7, 2, 7, 2, 7, -1, 2, -1, -1]
    • Expected Output: 0
    • Justification: 0 is the unique number appearing once, while 7, 2 and -1 appear three times.

Solution

To solve this problem, we'll employ bitwise manipulation techniques, which are both space-efficient and run in linear time. The essence of this approach is to count the number of times each bit appears in all numbers. Since every number, except for one, appears exactly three times, a bit set in the unique number will contribute to the total count in a way that's not divisible by three. By iterating over each bit position and summing the occurrence of bits in that position across all numbers, we can determine which bits belong to the unique number. We'll then reconstruct this number from its bits.

This method is effective because it directly leverages the fixed repetition count and the bitwise nature of integers to sidestep the need for additional memory that would be required for hash table-based approaches.

Step-by-Step Algorithm

  1. Initialize a Bit Count Array:

    • Create an array bitCount with a size equal to the number of bits in an integer (32 bits for standard integers). This array will track the count of 1s in each bit position across all numbers in the input array.
  2. Count Bits for Each Number:

    • Iterate over each number in the input array.
    • For each number, iterate over each bit position from 0 to 31.
      • Right shift the number by i bits and apply a bitwise AND with 1 to isolate the bit at position i.
      • Add the result to the ith position in the bitCount array to count the occurrences of 1s in this bit position across all numbers.
  3. Reconstruct the Single Number:

    • Initialize a variable result to 0. This variable will store the unique number that appears exactly once.
    • Iterate over the bitCount array from 0 to 31 (for each bit position).
      • If the count in bitCount[i] is not divisible by 3, it means this bit is set in the unique number (since all other numbers appear exactly three times).
      • Set the ith bit in result by using a bitwise OR with (1 << i).
  4. Return the Unique Number:

    • Return the result, which now contains the unique number reconstructed from its bits.

Algorithm Walkthrough

Let's walkthrough the Input: nums = [0, 7, 2, 7, 2, 7, -1, 2, -1, -1]

  1. Initialize bitCount Array:

    • Before processing: bitCount = [0, 0, 0, ..., 0] (32 zeroes for 32-bit positions).
  2. Process Each Number and Update bitCount:

    • Process 0:

      • No bits to update for 0. bitCount remains unchanged.
    • First 7 encountered:

      • 7 in binary is 000...0111. Update counts for positions 0, 1, and 2.
      • After processing: bitCount = [1, 1, 1, 0, 0, ..., 0].
    • First 2 encountered:

      • 2 in binary is 000...0010. Update count for position 1.
      • After processing: bitCount = [1, 2, 1, 0, 0, ..., 0].
    • Second 7 encountered:

      • Update counts for positions 0, 1, and 2 again.
      • After processing: bitCount = [2, 3, 2, 0, 0, ..., 0].
    • Second 2 encountered:

      • Update count for position 1.
      • After processing: bitCount = [2, 4, 2, 0, 0, ..., 0].
    • Third 7 encountered:

      • Update counts for positions 0, 1, and 2 again.
      • After processing: bitCount = [3, 5, 3, 0, 0, ..., 0].
    • Third 2 encountered:

      • Update count for position 1.
      • After processing: bitCount = [3, 6, 3, 0, 0, ..., 0].
    • First -1 encountered:

      • -1 in binary (two's complement) is all 1s. Update all positions.
      • After processing: bitCount becomes incremented by 1 at each position, e.g., [4, 7, 4, 1, 1, ..., 1].
    • Second -1 encountered:

      • Again, update all positions by 1.
      • After processing: bitCount increments by 1 at each position again, e.g., [5, 8, 5, 2, 2, ..., 2].
    • Third -1 encountered:

      • Once more, update all positions by 1.
      • After processing: bitCount increments by 1 at each position, e.g., [6, 9, 6, 3, 3, ..., 3].
  3. Reconstruct the Single Number:

    • Iterate over bitCount. Look for positions where the count is not a multiple of 3.
    • Since every number except 0 has modified the bitCount, and since 0 does not contribute to any bit position, the only way to detect 0 is by realizing there's no bit position with a count not divisible by 3 that would contribute to constructing a non-zero result.
    • The absence of such positions confirms the unique number does not contribute to any bit's count, identifying the unique number as 0.
  4. Return the Unique Number:

    • The final result is calculated to be 0, which correctly identifies it as the unique number not conforming to the thrice occurrence pattern in the input array.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity is , where (N) is the length of the input array and (K) is the number of bits in an integer (which is a constant, typically 32 for standard integer representations). Since K is constant, the time complexity simplifies to , indicating linear time complexity with respect to the size of the input.

Space Complexity

The space complexity is , due to the additional array bitCount used to keep track of the count of each bit across all numbers in the input array. Since K is a constant (32 for an integer), the space complexity simplifies to , indicating constant space complexity.

Single Number II (medium)
4Sum II (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity